<?php

namespace IDock\Insurance\DBIC\Request;

use IDock\Insurance\DBIC\DBICEnums;
use IDock\Insurance\DBIC\Response\PremiumInquiryResponse;
use IDock\Printer\NonCar\NonCarSubCoveragePrinter;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumChargingPileVisitor;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;

class PremiumInquiryRequest extends AllDBICRequest
{
    protected $route = 'dbic/qos/channel/quote/enquiry';

    protected $response = PremiumInquiryResponse::class;

    protected $urlTip = '报价接口';

    private $C16002 = false;

    private $C16003 = false;

    /*** @var  PremiumInquiryVisitor $visitor */
    protected $visitor;

    public function generate(): array
    {
        $data = [
            'main' => $this->mainData(),
            'car' => $this->carData(),
            'kindList' => $this->coverageList(),
            'carshipTax' => $this->carShipTax(),
            'insuredList' => $this->insuredList(),
        ];

        if ($chargingList = $this->chargingList()) {
            $data['chargingPileList'] = $chargingList;
        }

        return $data;
    }

    private function riskCode(): string
    {
        if (!$this->visitor->biStartData) {
            return '';
        }
        if ($this->visitor->isNewEnergy) {
            return '0515';
        }
        return '0510';
    }

    /**
     * 主信息
     * @return array
     */
    private function mainData(): array
    {
        $data = [
            //代理人代码
            'agentCode' => $this->visitor->getExtInfoVisitor()->argc['agentCode'] ?? '',
            //代理协议号
            'agreementNo' => $this->visitor->getExtInfoVisitor()->argc['agreementNo'] ?? '',
            'biStatus' => $this->visitor->biStartData ? 1 : 0,
            'ciStatus' => $this->visitor->ciStartData ? 1 : 0,
            'riskCodeBi' => $this->riskCode(),
            'comCode' => $this->visitor->getExtInfoVisitor()->argc['comCode'] ?? '',
            'endTimeBI' => $this->visitor->biEndData,
            'endTimeCI' => $this->visitor->ciEndData,
            'healthStatus' => $this->visitor->getNonCarInquiryVisitor()->getNonCarList() ? 1 : 0,

            'specialChannel' => "",
            'inputSysCode' => $this->visitor->getExtInfoVisitor()->argc['inputSysCode'] ?? '',
            'operatorCode' => $this->visitor->getExtInfoVisitor()->argc['operatorCode'] ?? '',
            'propertyStatus' => 0,
            'startTimeBI' => $this->visitor->biStartData,
            'startTimeCI' => $this->visitor->ciStartData,
            'handler1Code' => $this->visitor->getExtInfoVisitor()->argc['handler1Code'] ?? '',
            'expectedDiscount' => $this->visitor->getExtInfoVisitor()->expectedDiscount,
            'effectFlag' => 0,
        ];

        ////即时生效
        if ($this->visitor->ciEffectFlag or $this->visitor->biEffectFlag) {
            $data['effectFlag'] = 1;
            $data['effectTime'] = $this->visitor->ciEffectFlag ? $this->visitor->ciStartData : $this->visitor->biStartData;

            if ($this->visitor->biEffectFlag) {
                $data['endTimeBI'] = date('Y-m-d 00:00:00',strtotime('+1 day',strtotime($data['endTimeBI'])));
            }

            if ($this->visitor->ciEffectFlag) {
                $data['endTimeCI'] = date('Y-m-d H:00:00', strtotime('+1 year',strtotime($data['startTimeCI'])));
            }
        }

        //团车渠道 单交才选 私家燃油单交
        //if ($this->visitor->getCiStartData() and !$this->visitor->getBiStartData() and $this->visitor->getVehicleVisitor()->energyTypeCode == 'E01') {
            $data['specialChannel'] = $this->visitor->getExtInfoVisitor()->argc['specialChannel'] ?? '';
        //}
        //非车
        if(!empty($this->visitor->getNonCarInquiryVisitor()->getNonCarList())){
            $data['relateInsureFlag'] = 1;

        }
        return $data;
    }

    /**
     * 车辆信息
     * @return array
     */
    private function carData(): array
    {
        $data = [
            'birthDay' => '',
            'brandName' => $this->visitor->getVehicleVisitor()->vehicleName,
            'carKindCode' => DBICEnums::$carKindCode[$this->visitor->getVehicleVisitor()->carKindCode] ?? '',
            'carOwner' => $this->visitor->getOwnerVisitor()->name,
            'chgOwnerFlag' => ($this->visitor->getVehicleVisitor()->isTransfer or $this->visitor->getVehicleVisitor()->isCiTransfer) ? '1' : '0',
            'completeKerBMass' => (string)((float)($this->visitor->getVehicleVisitor()->wholeWeight) / 1000),
            'countryNature' => $this->visitor->getVehicleVisitor()->vehicleImport ? 'A' : 'B',
            'credentialCode' => DBICEnums::$certificateTypeCode[$this->visitor->getOwnerVisitor()->certificateTypeCode] ?? '',
            'credentialNo' => $this->visitor->getOwnerVisitor()->certificateNo,
            'engineNo' => $this->visitor->getVehicleVisitor()->engineNo,
            'enrollDate' => $this->visitor->getVehicleVisitor()->firstRegisterDate,
            'exhaustScale' => $this->visitor->getVehicleVisitor()->vehicleExhaust,
            'frameNo' => $this->visitor->getVehicleVisitor()->vin,
            'fuelType' => DBICEnums::$energyType[$this->visitor->getVehicleVisitor()->energyTypeCode] ?? '',
            'licenseKindCode' => '02',
            'licenseNo' => $this->visitor->getVehicleVisitor()->licenseNo,
            'modelCode' => $this->visitor->getVehicleVisitor()->vehicleModelCode,
            'platModelCode' => $this->visitor->getVehicleVisitor()->argc['platModelCode'] ?? '',
            'productType' => '0101',
            'purchasePrice' => $this->visitor->getVehicleVisitor()->vehiclePrice,
            'seatCount' => $this->visitor->getVehicleVisitor()->vehicleSeat,
            'sex' => '',
            'specialCarFlag' => '0',
            'tonCount' => (string) floatval(floatval($this->visitor->getVehicleVisitor()->vehicleTonnage ?? 0) / 1000),
            'transferDate' => $this->visitor->getVehicleVisitor()->transferDate,
            'useNatureCode' => DBICEnums::$causeType[$this->visitor->getVehicleVisitor()->causeType] ?? '',
            'vehicleOwnerNature' => DBICEnums::$attachNature[$this->visitor->getVehicleVisitor()->attachNature] ?? '',
            'vehicleType' => $this->visitor->getVehicleVisitor()->vehicleStyleCode,
            'firstBeneficiary' => 0,
            'carOwnerPhone' => $this->visitor->getOwnerVisitor()->mobile,
            'riskTruckFlag' => 0,
            'onlineCarFlag' => 0,
            'carValueType' => '1',
            'negotiationValue' => $this->visitor->getVehicleVisitor()->actualValue,
            'loanVehicleFlag' => 0,
            'colorCode' => DBICEnums::$vehicleColor[$this->visitor->vehicleVisitor->vehicleColor] ?? '',
        ];

        if ($this->visitor->getVehicleVisitor()->negotiatedValue and $this->visitor->getVehicleVisitor()->negotiatedValue != $this->visitor->getVehicleVisitor()->actualValue) {
            $data['carValueType'] = '2';
            $data['negotiationValue'] = $this->visitor->getVehicleVisitor()->negotiatedValue;
        }

        $ownerType = $this->visitor->getOwnerVisitor()->certificateTypeCode;
        $ownerNo = $this->visitor->getOwnerVisitor()->certificateNo;
        if ($ownerType == '01' and (strlen($ownerNo) == '18')) {
            $data['birthDay'] = substr($ownerNo, 6, 8);
            $data['birthDay'] = date('Y-m-d', strtotime($data['birthDay']));

            $data['sex'] = substr($ownerNo, 16, 1);
            $data['sex'] = $data['sex'] % 2 ? '1' : '2';
        }

        //车主 和 被保人 信息一致
        if ($this->visitor->getOwnerVisitor()->certificateNo == $this->visitor->getInsuredVisitor()->certificateNo) {
            $data['carInsuredRelation'] = '1';
        } else {
            $data['carInsuredRelation'] = '3';
        }

        return $data;
    }

    /**
     * 险种信息
     * @return array
     */
    private function coverageList(): array
    {
        $list = [];
        $no = 1;

        $coverageList = $this->visitor->getCoverageVisitorList();
        $coverageList = array_combine(array_column($coverageList, 'coverageCode'), $coverageList);

        foreach ($coverageList as $coverage) {

            /*** @var PremiumCoverageVisitor $coverage */

            //交强险去除
            if ($coverage->coverageCode == 'C01001') {
                continue;
            }

            if ($coverage->coverageCode == 'C16002') {
                $this->C16002 = true;
            }

            if ($coverage->coverageCode == 'C16003') {
                $this->C16003 = true;
            }

            $one = [
                'itemkindNo' => (string)$no,
                'kindCode' => DBICEnums::$coverageCode[$coverage->coverageCode],
                'quanTity' => $coverage->quantity,
                'unitAmount' => $coverage->unitAmount,
                'amount' => $coverage->amount,
                'rate' => $coverage->rate,
                'deductPercent' => '0',
            ];

            if (!$one['kindCode']) {
                continue;
            }

            //车损险
            if ($one['kindCode'] == 'A') {
                $one['value'] = '0';
                $one['amount'] = $this->visitor->getVehicleVisitor()->negotiatedValue?: $this->visitor->getVehicleVisitor()->actualValue;
            }

            if ($one['kindCode'] == 'A') {
                $one['deductPercent'] = $coverageList['C02006']->deductionRate ?? $coverageList['C12006']->deductionRate ?? '0';
            }

            if ($one['kindCode'] == 'B') {
                $one['deductPercent'] = $coverageList['C03005']->deductionRate ?? $coverageList['C13005']->deductionRate ?? '0';
            }

            if ($one['kindCode'] == 'D3') {
                $one['deductPercent'] = $coverageList['C04004']->deductionRate ?? $coverageList['C14004']->deductionRate ?? '0';
            }
            if ($one['kindCode'] == 'D4') {
                $one['deductPercent'] = $coverageList['C05004']->deductionRate ?? $coverageList['C15004']->deductionRate ?? '0';
            }

            //司机险
            if ($one['kindCode'] == 'D3') {
                $one['quanTity'] = '1';
                $one['unitAmount'] = $one['amount'];
            }

            //乘客险
            if ($one['kindCode'] == 'D4') {
                $one['quanTity'] = (string)($this->visitor->getVehicleVisitor()->vehicleSeat - 1);
            }

            //保外就医乘客
            if ($one['kindCode'] == 'H3_D4') {
                $one['quanTity'] = (string)($this->visitor->getVehicleVisitor()->vehicleSeat - 1);
                $one['unitAmount'] = $one['amount'];
                $one['amount'] = (string)($one['quanTity'] * $one['unitAmount']);
            }

            //修理险总保额
            if ($one['kindCode'] == 'T') {
                $one['amount'] = (string)($one['quanTity'] * $one['unitAmount']);
            }

            if (in_array($one['kindCode'], ['H4_01', 'H4_02', 'H4_03', 'H4_04'])) {
                $one['quanTity'] = $coverage->serviceTimes;
            }

            $no += 1;

            $list[] = $one;
        }
        //非车
        if(!empty($this->visitor->getNonCarInquiryVisitor()->getNonCarList())){
            /**@var NonCarProductVisitor $noCarPlan */
            $noCarPlan = $this->visitor->getNonCarInquiryVisitor()->getNonCarList()[0] ?? [];
            $amount = 0;
            foreach ($noCarPlan->subCoverage as $val){
                /**@var NonCarSubCoveragePrinter $val */
                $amount += floatval($val->amount);
            }
            $list[] = [
                'itemkindNo' => count($list) + 1,
                'kindCode' => $noCarPlan->productCode,
                'quanTity' => intval($noCarPlan->insuredNum),
                'unitAmount' => $noCarPlan->premium,
                'amount' => floatval($noCarPlan->premium *  $noCarPlan->insuredNum),
                'kindFlag' => '1',
            ];
        }
        return $list;
    }

    /**
     * 充电桩
     * @return array
     */
    private function chargingList(): array
    {
        if (!$this->C16003 and !$this->C16002) {
            return [];
        }
        $list = [];
        $no = 1;

        foreach ($this->visitor->getChargingPileVisitorList() as $visitor) {

            /*** @var PremiumChargingPileVisitor $visitor */

            $one = [
                'itemkindNo' => (string)$no,
                'chargingPostType' => DBICEnums::$chargingPileKind[$visitor->chargingPileKind] ?? '',
                'chargingPostCode' => $visitor->chargingPileCode,
                'chargingPostAddress' => $visitor->chargingPileAddress,
                'chargingPostAddressType' => DBICEnums::$chargingPileAddressType[$visitor->chargingPileAddressType] ?? '',
                'chargingPostKind' => $visitor->chargingPileType,
                'chargingPostYearLimit' => '1',
            ];

            //C1
            if ($this->C16002) {
                $kindList = [
                    'itemkindNo' => (string)$no,
                    'kindCode' => 'C1',
                    'startDate' => date('Y-m-d', strtotime($this->visitor->biStartData)),
                    'startHour' => date('H', strtotime($this->visitor->biStartData)),
                    'endDate' => date('Y-m-d', strtotime($this->visitor->biStartData)),
                    'endHour' => date('H', strtotime($this->visitor->biStartData)),
                    'amount' => $visitor->lossAmount
                ];

                $one['chargingKindList'][] = $kindList;
            }

            //C2
            if ($this->C16003) {
                $kindList = [
                    'itemkindNo' => (string)$no,
                    'kindCode' => 'C2',
                    'startDate' => date('Y-m-d', strtotime($this->visitor->biStartData)),
                    'startHour' => date('H', strtotime($this->visitor->biStartData)),
                    'endDate' => date('Y-m-d', strtotime($this->visitor->biStartData)),
                    'endHour' => date('H', strtotime($this->visitor->biStartData)),
                    'amount' => $visitor->liabilityAmount
                ];

                $one['chargingKindList'][] = $kindList;
            }

            $no += 1;
            $list[] = $one;
        }
        return $list;

    }

    /**
     * 车船税
     * @return array
     */
    private function carShipTax(): array
    {
        $taxVisitor = $this->visitor->getCarTaxVisitor();

        return [
            'decucationDueType' => $taxVisitor->taxReductionCode,
            'deducation' => $taxVisitor->taxExemption,
            'deducationDocumentNumber' => $taxVisitor->taxDocumentNumber,
            'deducationDueCode' => DBICEnums::$taxReductionReasonCode[$taxVisitor->taxReductionReasonCode] ?? '',
            'deducationDuePropotion' => $taxVisitor->taxFreeRate,
            'taxDepartment' => $taxVisitor->taxDepartment,
            'taxDepartmentDerate' => $taxVisitor->taxDepartmentCode,
            'taxDocumentDate' => $taxVisitor->taxDocumentDate,
            'taxDocumentNumber' => $taxVisitor->taxDocumentNumber,
            'taxEndDate' => $taxVisitor->taxEndDate,
            'taxPaidAreaCode' => $taxVisitor->taxPaidAreaCode,
            'taxRelief' => DBICEnums::$taxTypeCode[$taxVisitor->taxTypeCode] ?? '',
            'taxStartDate' => $taxVisitor->taxStartDate,
            'taxDefault' => '',
            'overrdue' => '',
        ];
    }

    /**
     * 关系人
     * @return array
     */
    private function insuredList(): array
    {
        $applicantVisitor = $this->visitor->getApplicantVisitor();
        $insuredVisitor = $this->visitor->getInsuredVisitor();
        $ownerVisitor = $this->visitor->getOwnerVisitor();

        if ((DBICEnums::$identifyType[$insuredVisitor->certificateTypeCode] ?? '') == 10) {
            throw new \Exception('投保人被保人不支持组织机构代码证，请使用用统一信用代码');
        }

        if ((DBICEnums::$identifyType[$ownerVisitor->certificateTypeCode] ?? '') == 10) {
            throw new \Exception('投保人被保人不支持组织机构代码证，请使用用统一信用代码');
        }

        return [
            [
                //投保人
                'insuredName' => $applicantVisitor->name,
                'identifyType' => DBICEnums::$identifyType[$applicantVisitor->certificateTypeCode] ?? '',
                'idenfityNumber' => $applicantVisitor->certificateNo,
                'insuredFlag' => '2',
                'insuredNature' => '3',
                'insuredType' => DBICEnums::$relationTypeCode[$applicantVisitor->typeCode] ?? '',
                'mobileNumber' => $applicantVisitor->mobile,
                'email' => $applicantVisitor->email,
            ],
            [
                //被保人
                'insuredName' => $insuredVisitor->name,
                'identifyType' => DBICEnums::$identifyType[$insuredVisitor->certificateTypeCode] ?? '',
                'idenfityNumber' => $insuredVisitor->certificateNo,
                'insuredFlag' => '1',
                'insuredNature' => '3',
                'insuredType' => DBICEnums::$relationTypeCode[$insuredVisitor->typeCode] ?? '',
                'mobileNumber' => $insuredVisitor->mobile,
                'email' => $insuredVisitor->email,
            ],
            [
                //车主
                'insuredName' => $ownerVisitor->name,
                'identifyType' => DBICEnums::$identifyType[$ownerVisitor->certificateTypeCode] ?? '',
                'idenfityNumber' => $ownerVisitor->certificateNo,
                'insuredFlag' => '3',
                'insuredNature' => '3',
                'insuredType' => DBICEnums::$relationTypeCode[$ownerVisitor->typeCode] ?? '',
                'mobileNumber' => $ownerVisitor->mobile,
                'email' => $ownerVisitor->email,
            ]
        ];


    }
}
